<template>
  <div class="bar-chart-container">
    <el-card shadow="hover">
      <div slot="header" class="chart-header">
        <span>订单数量统计（垂直柱状图）</span>
        <!-- <el-select
          v-model="timeRange"
          placeholder="选择时间范围"
          size="small"
          @change="handleTimeChange"
        >
          <el-option label="近7天" value="7day"></el-option>
          <el-option label="近30天" value="30day"></el-option>
        </el-select> -->
      </div>
      <div id="verticalBarChart" style="width: 100%; height: 400px"></div>
    </el-card>
  </div>
</template>

<script>
import { getOrderCount } from "@/api/orderApi";
import * as echarts from "echarts";

export default {
  name: "VerticalBarChart",
  data() {
    return {
      timeRange: "7day",
      chartInstance: null,
      chartData: {
        // 默认值
        dates: ["2025-03-24", "2025-03-25", "2025-03-26", "2025-03-27"],
        series: [
          { name: "已完成", data: [0, 1, 4, 3] },
          { name: "待付款", data: [0, 0, 2, 0] },
          { name: "已取消", data: [1, 2, 0, 0] },
        ],
      },
    };
  },
  mounted() {
    this.initChart();
    this.loadData();
    window.addEventListener("resize", this.resizeChart);
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    window.removeEventListener("resize", this.resizeChart);
  },
  methods: {
    // 初始化图表
    initChart() {
      this.chartInstance = echarts.init(
        document.getElementById("verticalBarChart")
      );
      this.renderChart();
    },

    loadData() {
      // 读取数据 如果是默认数据则加载失败了
      getOrderCount({})
        .then((res) => {
          console.log(res);
          this.chartData = res;
          this.renderChart();
        })
        .catch((err) => {
          this.$message.error("数据加载失败", err);
        });
    },

    // 渲染图表
    renderChart() {
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          formatter: (params) => {
            let html = params[0].axisValue + "<br>";
            params.forEach((item) => {
              html += `${item.marker} ${item.seriesName}: ${item.value}<br>`;
            });
            html += `<b>总量: ${params.reduce(
              (sum, cur) => sum + cur.value,
              0
            )}</b>`;
            return html;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.chartData.dates,
          axisLabel: {
            color: "#606266", // Element UI 文本色
            rotate: 30, // 标签旋转避免重叠
            formatter: (value) => {
              // 格式化日期显示，例如：03-24
              return value.split("-").slice(1).join("-");
            },
          },
          axisLine: {
            lineStyle: {
              color: "#DCDFE6", // Element UI 边框色
            },
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#606266",
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              color: "#EBEEF5", // Element UI 分割线色
            },
          },
        },
        series: this.chartData.series.map((item) => ({
          name: item.name,
          type: "bar",
          data: item.data,
          barGap: 0,
          barWidth: "20%", // 调窄柱宽适应多系列
          itemStyle: {
            color: this.getStatusColor(item.name), // 按状态分配颜色
            borderRadius: [4, 4, 0, 0],
          },
          label: { show: true },
        })),
        legend: { data: this.chartData.series.map((item) => item.name) },
      };
      this.chartInstance.setOption(option);
    },

    getStatusColor(status) {
      const colors = {
        已完成: "#67C23A", // Element UI success
        已付款: "#E6A23C", // Element UI warning
        退单中: "#F56C6C", // Element UI danger
        退单中: "#F56C6C", // Element UI danger
      };
      return colors[status] || "#409EFF";
    },

    // 窗口缩放适配
    resizeChart() {
      this.chartInstance?.resize();
    },

    // 时间范围切换
    handleTimeChange() {
      this.loadData();
    },
  },
};
</script>

<style scoped>
.bar-chart-container {
  padding: 20px;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>